package Text;

import jdk.swing.interop.SwingInterOpUtils;

import java.util.Arrays;

public class MyArrayList implements IList {
    public  int[] elem;
    public int UsedSize;
    public MyArrayList(){
        this.elem=new int[10];
    }


    @Override
    public void add(int data) {
        if(isFull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        this.elem[UsedSize]=data;
        this.UsedSize++;
    }

    @Override
    public void add(int pos, int data) {
        try {
            CheckPosOfAdd(pos);
        }catch (PosNoyLedalException e){
            e.printStackTrace();
        }
        if(isFull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        int i=UsedSize-1;
        while(i>=pos){
            elem[i+1]=elem[i];
            i--;
        }
        elem[pos]=data;
        UsedSize++;


    }
    private void CheckPosOfAdd(int pos) throws PosNoyLedalException{
        if(pos<0||pos>UsedSize){
            throw new PosNoyLedalException("pos位置不合法");
        }
    }

    @Override
    public boolean containss(int toFind) {
        for (int i = 0; i <UsedSize ; i++) {
            if(elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i <UsedSize ; i++) {
            if (elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get (int pos) {
        try {
            CheckPosOfGet(pos);
        }catch (PosNoyLedalException e){
            e.printStackTrace();
        }
        return elem[pos];
    }
    private void CheckPosOfGet (int pos) throws PosNoyLedalException{
        if(pos<0||pos>=UsedSize){
            throw new ClassCastException("get获取元素时pos位置不合法");
        }
    }

    @Override
    public void set(int pos, int value) {
        try {
            CheckPosOfGet(pos);
        }catch (PosNoyLedalException e ){
            e.printStackTrace();
        }
        elem[pos]=value;
    }

    @Override
    public void remove(int toRmove) {
        //1 先查找要删除的数
        int pos=indexOf(toRmove);
        if(pos==-1){
            System.out.println("没有要删除的数字");
            return;
        }
        for (int i = pos; i < UsedSize-1; i++) {
            elem[i]=elem[i+1];
        }
        UsedSize--;

    }

    @Override
    public int size() {
        return UsedSize;
    }

    @Override
    public void clear() {
        UsedSize=0;
    }

    @Override
    public boolean isFull() {
        return UsedSize==elem.length;
    }

    @Override
    public void display() {
        for (int i = 0; i < UsedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println( );
    }


}
